package com.test.ad.demo;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

/**
 * 简易扫雷页面：9x9 网格，点击翻开，长按标记。
 * 这里实现一个极简本地玩法以满足页面展示需求。
 */
public class GameFragment extends Fragment {

    private static final int ROWS = 5;
    private static final int COLS = 5;
    private static final int MINES = 5;

    private boolean[][] isMine = new boolean[ROWS][COLS];
    private int[][] around = new int[ROWS][COLS];
    private boolean[][] opened = new boolean[ROWS][COLS];
    private boolean[][] flagged = new boolean[ROWS][COLS];
    private boolean firstClick = true;
    private GridLayout grid;
    private TextView tvStatus;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_game, container, false);
        grid = root.findViewById(R.id.grid);
        tvStatus = root.findViewById(R.id.tv_status);

        grid.setColumnCount(COLS);
        grid.setRowCount(ROWS);

        setupBoard(-1, -1);
        inflateCells(inflater);

        root.findViewById(R.id.btn_restart).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setupBoard(-1, -1);
                refreshCells();
            }
        });

        ImageView btnDetail = root.findViewById(R.id.btn_earnings_detail);
        if (btnDetail != null) {
            btnDetail.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startActivity(new android.content.Intent(getActivity(), EarningsActivity.class));
                }
            });
        }

        return root;
    }

    private void setupBoard(int safeR, int safeC) {
        for (int r = 0; r < ROWS; r++) {
            for (int c = 0; c < COLS; c++) {
                isMine[r][c] = false;
                around[r][c] = 0;
                opened[r][c] = false;
                flagged[r][c] = false;
            }
        }
        firstClick = true;
        tvStatus.setText("剩余地雷：" + MINES);

        // 先不布雷，首击时根据安全位置再布雷
    }

    private void placeMines(int safeR, int safeC) {
        int placed = 0;
        java.util.Random random = new java.util.Random();
        while (placed < MINES) {
            int r = random.nextInt(ROWS);
            int c = random.nextInt(COLS);
            if (isMine[r][c]) continue;
            if (r == safeR && c == safeC) continue;
            isMine[r][c] = true;
            placed++;
        }
        // 计算提示数字
        for (int r = 0; r < ROWS; r++) {
            for (int c = 0; c < COLS; c++) {
                if (isMine[r][c]) {
                    around[r][c] = -1;
                    continue;
                }
                int cnt = 0;
                for (int dr = -1; dr <= 1; dr++) {
                    for (int dc = -1; dc <= 1; dc++) {
                        if (dr == 0 && dc == 0) continue;
                        int nr = r + dr, nc = c + dc;
                        if (nr >= 0 && nr < ROWS && nc >= 0 && nc < COLS && isMine[nr][nc]) cnt++;
                    }
                }
                around[r][c] = cnt;
            }
        }
    }

    private void inflateCells(LayoutInflater inflater) {
        grid.removeAllViews();
        for (int r = 0; r < ROWS; r++) {
            for (int c = 0; c < COLS; c++) {
                final int fr = r, fc = c;
                final TextView cell = (TextView) inflater.inflate(R.layout.view_cell, grid, false);
                cell.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        onOpen(fr, fc, (TextView) v);
                    }
                });
                cell.setOnLongClickListener(new View.OnLongClickListener() {
                    @Override
                    public boolean onLongClick(View v) {
                        toggleFlag(fr, fc, (TextView) v);
                        return true;
                    }
                });
                grid.addView(cell);
            }
        }
    }

    private void refreshCells() {
        int child = 0;
        int flags = 0;
        for (int r = 0; r < ROWS; r++) {
            for (int c = 0; c < COLS; c++) {
                TextView cell = (TextView) grid.getChildAt(child++);
                if (flagged[r][c]) {
                    cell.setText("🚩");
                } else if (!opened[r][c]) {
                    cell.setText("*");
                    cell.setEnabled(true);
                } else if (isMine[r][c]) {
                    cell.setText("💣");
                    cell.setEnabled(false);
                } else {
                    int n = around[r][c];
                    cell.setText(n == 0 ? "" : String.valueOf(n));
                    cell.setEnabled(false);
                }
                if (flagged[r][c]) flags++;
            }
        }
        tvStatus.setText("剩余地雷：" + Math.max(0, MINES - flags));
    }

    private void onOpen(int r, int c, TextView view) {
        if (flagged[r][c] || opened[r][c]) return;
        if (firstClick) {
            placeMines(r, c);
            firstClick = false;
        }
        opened[r][c] = true;
        if (isMine[r][c]) {
            // 失败：全部显示
            revealAll(true);
            return;
        }
        if (around[r][c] == 0) {
            floodOpen(r, c);
        }
        checkWin();
        refreshCells();
    }

    private void toggleFlag(int r, int c, TextView view) {
        if (opened[r][c]) return;
        flagged[r][c] = !flagged[r][c];
        refreshCells();
    }

    private void floodOpen(int r, int c) {
        java.util.ArrayDeque<int[]> dq = new java.util.ArrayDeque<>();
        dq.add(new int[]{r, c});
        while (!dq.isEmpty()) {
            int[] cur = dq.removeFirst();
            int cr = cur[0], cc = cur[1];
            for (int dr = -1; dr <= 1; dr++) {
                for (int dc = -1; dc <= 1; dc++) {
                    int nr = cr + dr, nc = cc + dc;
                    if (nr < 0 || nr >= ROWS || nc < 0 || nc >= COLS) continue;
                    if (opened[nr][nc] || flagged[nr][nc] || isMine[nr][nc]) continue;
                    opened[nr][nc] = true;
                    if (around[nr][nc] == 0) dq.addLast(new int[]{nr, nc});
                }
            }
        }
    }

    private void revealAll(boolean failed) {
        for (int r = 0; r < ROWS; r++) {
            for (int c = 0; c < COLS; c++) {
                opened[r][c] = true;
            }
        }
        refreshCells();
        tvStatus.setText(failed ? "踩雷了，点击‘重新开始’再试一次" : "恭喜通关！");
    }

    private void checkWin() {
        for (int r = 0; r < ROWS; r++) {
            for (int c = 0; c < COLS; c++) {
                if (!isMine[r][c] && !opened[r][c]) return;
            }
        }
        revealAll(false);
    }
}


